home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11076 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  64 lines

  1. Path: news.halcyon.com!usenet
  2. From: normanb@halcyon.com (Norm Bryar)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: const FAQ?
  5. Date: Tue, 12 Mar 1996 16:28:54 GMT
  6. Organization: Northwest Nexus Inc.
  7. Message-ID: <4i48ms$qtc@news.halcyon.com>
  8. References: <31433D9F.4F81@eskimo.com>
  9. NNTP-Posting-Host: blv-pm3-ip12.halcyon.com
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. Sean Forde <seano@eskimo.com> wrote:
  13.  
  14. >Has anyone ever figured out what all the different ways of using the 
  15. >keyword "const" mean? Does a chart illustrating this exist? Most 
  16. >books lightly touch this subject.
  17.  
  18. >    -Sean
  19.  
  20. Well,...
  21. Declarations are read from right to left, like yiddish or something.
  22.  
  23. char * const   pString;       // a constant pointer to (normal) chars
  24. const char *  pcString;     // a pointer to a character constant
  25.  
  26. Const-correctness is a very nice thing to write into your function
  27. prototypes: it promises that when someone passes in an argument,
  28. especially by reference or pointer, you won't have screwed with it.
  29. Callers needn't make an auxilliary copy or anything before calling
  30. you.
  31.  
  32. When creating a const value, the initialization should occur when the
  33. variable is defined.
  34.  
  35. const int  seconds_per_hour = 3600;    // initialized constant
  36. seconds_per_hour = 4500;        // ERROR!
  37.  
  38.  
  39. Class methods can be declared/defined with const as a promise that
  40. this class method will not alter any member of the class.
  41.  
  42. class X
  43. {
  44.         // save writes members to the archive,
  45.         // but promises not to change any of 'em.
  46.     BOOL  Save( CArchive & archive ) const;
  47.  
  48.         // The equality operator promises
  49.         // not to change anybody, x1 or x2,
  50.         // in the call if( x1 == x2 )
  51.     BOOL operator==( const X & toCompare ) const;
  52.  
  53. };
  54.  
  55. Again, const correctness is nice and should be part of your
  56. development effort.  Conventional wisdom says, however, it's very
  57. difficult and probably not worth it to retro-fit const-correctness
  58. into legacy code.
  59.  
  60. That's largely it, I should think.  Helpful?
  61.  
  62.                     --Norm 
  63.  
  64.